﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YS.Domain.IoT.Extension
{
    public static class BufferExtension
    {
        // 定义一个方法来移除字节数组末尾的空白字符
        public static byte[] RemoveTrailingWhitespace(this byte[] source)
        {
            if (source == null || source.Length == 0)
                return source;

            // 从末尾开始遍历，找到最后一个非空白字符的位置
            int lastIndex = source.Length - 1;
            while (lastIndex >= 0 && char.IsWhiteSpace((char)source[lastIndex]))
            {
                lastIndex--;
            }

            // 如果全是空白，则返回空数组；否则，返回截取后的数组
            return lastIndex == source.Length - 1 ? source : new ArraySegment<byte>(source, 0, lastIndex + 1).ToArray();
        }
        public static bool StartsWith(this byte[] source, byte[] prefix)
        {
            if (prefix.Length > source.Length)
                return false;

            for (int i = 0; i < prefix.Length; i++)
            {
                if (source[i] != prefix[i])
                    return false;
            }

            return true;
        }

        public static bool EndsWith(this byte[] source, byte[] suffix)
        {
            if (suffix.Length > source.Length)
                return false;

            int startIndex = source.Length - suffix.Length;
            for (int i = 0; i < suffix.Length; i++)
            {
                if (source[startIndex + i] != suffix[i])
                    return false;
            }

            return true;
        }
    }
}
